package ma.moliere.editique.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import ma.moliere.commun.FonctionnelleException;
import ma.moliere.editique.IGenerateurImpression;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

import org.richfaces.log.LogFactory;
import org.richfaces.log.Logger;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

public class GenerateurImpressionImpl implements IGenerateurImpression, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4211870044790351236L;
	private static Logger LOGGER = LogFactory.getLogger(GenerateurImpressionImpl.class);
	private DriverManagerDataSource dataSource;

	@Override
	public JasperPrint genererRecuPaiement(final List < Long > ids) throws FonctionnelleException {
		JasperPrint jasperPrint = null;
		try {
			// Class.forName("com.mysql.jdbc.Driver");
			// Connection conn = (Connection)
			// DriverManager.getConnection("jdbc:mysql://localhost:3306/moliere?user=root&password=root");

			InputStream input = new FileInputStream(new File(
				"D:/Personnel/dev/projets/edition_moliere/recudepaiementreport.jrxml"));
			JasperDesign jasperDesign = JRXmlLoader.load(input);

			JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

			Map < String, Object > parameters = new HashMap < String, Object >();
			parameters.put("reglementId", ids);
			jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource.getConnection());

		} catch (JRException e) {
			LOGGER.error(e.getMessage());
			// throw new FonctionnelleException("Erreur technique  JASPER.");

		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage());
			throw new FonctionnelleException("Erreur technique fichier template introuvable.");
		} catch (SQLException e) {
			LOGGER.error(e.getMessage());
			throw new FonctionnelleException("Erreur technique de connexion à la base.");
		}
		return jasperPrint;
	}

	public void setDataSource(final DriverManagerDataSource dataSource) {
		this.dataSource = dataSource;
	}

}
